package com.puzzlebazar.client.util;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerRegistration;

public class GlassWindow extends SimplePanel 
	implements NativePreviewHandler {

	private static GlassWindow singleton = null;
	
	
	private final MyResizeHandler resizeHandler = new MyResizeHandler();

	private HandlerRegistration myResizeHandlerRegistration = null;
	private HandlerRegistration myPreviewHandlerRegistration = null;
	
	/**
	 * Cover the browser with a glass window
	 */
	public static void showGlassWindow(boolean white) {

		if( singleton == null ) singleton = new GlassWindow();
		if( white )
			DOM.setStyleAttribute(singleton.getElement(), "backgroundColor", "#ffffff");
		else
			DOM.setStyleAttribute(singleton.getElement(), "backgroundColor", "transparent");
			
		RootPanel.get().add( singleton, 0, 0 );
	}
	
	/**
	 * Removes the glass window from the browser
	 */
	public static void hideGlassWindow() {
		assert( singleton != null );
		singleton.removeFromParent();
	}

	/**
	 * Creates a new panel used to obscure control over the entire browser
	 */
	private GlassWindow() {
		setStyleName("glassWindow");
		DOM.setStyleAttribute(getElement(), "position", "fixed");
	    DOM.sinkEvents(getElement(),
	    		DOM.getEventsSunk(getElement()) | Event.MOUSEEVENTS | Event.KEYEVENTS );
	}

	@Override
	public void onPreviewNativeEvent(NativePreviewEvent event) {
		event.cancel();
	}
	
	@Override
	protected void onAttach() {
		super.onAttach();
		myResizeHandlerRegistration = Window.addResizeHandler( resizeHandler );		
	    myPreviewHandlerRegistration = Event.addNativePreviewHandler(this);
		adjustSize();
	}

	@Override
	protected void onDetach() {
		super.onDetach();
		if( myResizeHandlerRegistration != null )
			myResizeHandlerRegistration.removeHandler();
		myResizeHandlerRegistration = null;
		if( myPreviewHandlerRegistration != null )
			myPreviewHandlerRegistration.removeHandler();
		myPreviewHandlerRegistration = null;

	
	}

	private void adjustSize() {
		setPixelSize( Window.getClientWidth(), Window.getClientWidth() );		
	}
	
	private class MyResizeHandler implements ResizeHandler {
		@Override
		public void onResize(ResizeEvent event) {
			adjustSize();
		}
	}

}

